package radiostation;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import model.Artist;
import model.MusicGroup;
import radiostation.common.ArtistRepository;
import radiostation.common.MusicGroupRepository;

public class MusicGroupUI extends BaseJFrame {

    private MusicGroup selectedMusicGroup;
    private final EntityManager entityManager;
    private final MainUI parent;

    public MusicGroupUI(EntityManager entityManager, MainUI mainUI) {
        this.entityManager = entityManager;
        this.parent = mainUI;

        initComponents();

        // open in the center of the window
        setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        musicGroupQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT m FROM MusicGroup m");
        musicGroupList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(musicGroupQuery.getResultList());
        jScrollPane1 = new javax.swing.JScrollPane();
        musicGroupTable = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(800, 600));
        setResizable(false);

        musicGroupTable.setColumnSelectionAllowed(true);
        musicGroupTable.setName("musicGroupTable"); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, musicGroupList, musicGroupTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${formationDate}"));
        columnBinding.setColumnName("Ημερομηνία δημιουργίας");
        columnBinding.setColumnClass(java.util.Date.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(musicGroupTable);
        musicGroupTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        jButton1.setForeground(java.awt.Color.blue);
        jButton1.setText("Νέο");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createNewMusicGroup(evt);
            }
        });

        jButton3.setText("Επεξεργασία");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editSelectedMusicGroup(evt);
            }
        });

        jButton2.setForeground(java.awt.Color.red);
        jButton2.setText("Διαγραφή");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteSelectedMusicGroup(evt);
            }
        });

        jButton4.setText("Έξοδος");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4exitForm(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 830, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton4)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 506, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1)
                            .addComponent(jButton3)
                            .addComponent(jButton2))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton4)
                        .addContainerGap())))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void createNewMusicGroup(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createNewMusicGroup

        selectedMusicGroup = new MusicGroup(null);
        
        

        try {

            MusicGroupEditUI musicGroupEditUI = new MusicGroupEditUI(entityManager);
            musicGroupEditUI.setVisible(true);
            setEnabled(false);

            musicGroupEditUI.addWindowListener(new WindowListener() {
                public void windowClosed(WindowEvent arg0) {
                    if (((MyWindowEvent) arg0).exitAndSave) {

                        if (!entityManager.getTransaction().isActive()) {
                            entityManager.getTransaction().begin();
                        }

                        MusicGroup selectMusicGroup = musicGroupEditUI.getSelectedMusicGroup();
                        // Τον γράφω στην ΒΔ
                        entityManager.persist(selectMusicGroup);
                        entityManager.flush();

                        // add the artist in the list
                        musicGroupList.add(selectMusicGroup);

                        // Επέλεξέ τον στον πίνακα
                        int row = musicGroupList.size() - 1;
                        musicGroupTable.setRowSelectionInterval(row, row);
                        musicGroupTable.scrollRectToVisible(musicGroupTable.getCellRect(row, 0, true));

                        // commit transaction
                        entityManager.getTransaction().commit();

                    }

                    // enable current form
                    setEnabled(true);
                }

                public void windowActivated(WindowEvent arg0) {
                }

                public void windowClosing(WindowEvent arg0) {
                }

                public void windowDeactivated(WindowEvent arg0) {
                }

                public void windowDeiconified(WindowEvent arg0) {
                }

                public void windowIconified(WindowEvent arg0) {
                }

                public void windowOpened(WindowEvent arg0) {
                }
            });

        } catch (Exception e) {
            Exception eχ = e;
            throw e;
        }
    }//GEN-LAST:event_createNewMusicGroup

    private void editSelectedMusicGroup(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editSelectedMusicGroup
        // check if music group is selected

        int row = musicGroupTable.getSelectedRow();

        if (row == -1) {
            showWarningMessage("Δεν έχει επιλεχθεί συγκρότημα");
            return;
        }

        selectedMusicGroup = musicGroupList.get(row);

        try {
            MusicGroupEditUI musicGroupEditUI = new MusicGroupEditUI(selectedMusicGroup, entityManager);
            musicGroupEditUI.setVisible(true);
            setEnabled(false);

            musicGroupEditUI.addWindowListener(new WindowListener() {
                public void windowClosed(WindowEvent arg0) {

                    if (((MyWindowEvent) arg0).exitAndSave) {
                        MusicGroup editedMusicGroup = musicGroupEditUI.getSelectedMusicGroup();

                        try {
                            if (!entityManager.getTransaction().isActive()) {
                                entityManager.getTransaction().begin();
                            }
                            MusicGroupRepository musicGroupRepository = new MusicGroupRepository(entityManager);
                            MusicGroup stateMusicGroup = musicGroupRepository.findById(editedMusicGroup.getMusicGroupId());
//
                            stateMusicGroup.setName(editedMusicGroup.getName());
                            stateMusicGroup.setFormationDate(editedMusicGroup.getFormationDate());
                            stateMusicGroup.setArtistList(editedMusicGroup.getArtistList());
//                          
//                            //replace current table row with the new one
                            musicGroupList.set(row, stateMusicGroup);

                            musicGroupTable.setRowSelectionInterval(row, row);
                            musicGroupTable.scrollRectToVisible(musicGroupTable.getCellRect(row, 0, true));
                            
                            // commit transaction
                            entityManager.getTransaction().commit();
                        } catch (Exception e) {
                            entityManager.getTransaction().rollback();
                        }
                    }
                    // enable the current form
                    setEnabled(true);
                }

                public void windowActivated(WindowEvent arg0) {
                }

                public void windowClosing(WindowEvent arg0) {
                }

                public void windowDeactivated(WindowEvent arg0) {
                }

                public void windowDeiconified(WindowEvent arg0) {
                }

                public void windowIconified(WindowEvent arg0) {
                }

                public void windowOpened(WindowEvent arg0) {
                }
            });

        } catch (Exception e) {
            Exception eχ = e;
            throw e;
        }
    }//GEN-LAST:event_editSelectedMusicGroup

    private void deleteSelectedMusicGroup(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteSelectedMusicGroup

        // Έλεγχος αν έχει επιλεγεί καλλιτέχνης
        int row = musicGroupTable.getSelectedRow();

        if (row == -1) {
            // Αναδυόμενο παράθυρο
            JOptionPane.showMessageDialog(this, "Δεν έχει επιλεχθεί συγκρότημα", "Σφάλμα",
                    JOptionPane.WARNING_MESSAGE);
            return;
        }

        // Επιβεβαίωση διαγραφής
        int choice = JOptionPane.showConfirmDialog(this, "Διαγραφή συγκροτήματος;",
                "Επιβεβαίωση διαγραφής συγκροτήματος",
                JOptionPane.YES_NO_OPTION);

        if (choice != 0) {
            return;
        }

        // Ανάκτηση του καλλιτέχνη προς διαγραφή
        MusicGroup musicGroupToRemove = musicGroupList.get(row);
        
        musicGroupToRemove.getArtistList().stream().forEach((a) -> {
            a.getMusicGroupList().remove(musicGroupToRemove);
        });

        // Διαγραφή του καλλιτέχνη από την ΒΔ
        // Δημιουργία μίας νέας δοσοληψίας
        if (!entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().begin();
        }

        // remove music group from db
        entityManager.remove(musicGroupToRemove);

        // remove music group from list that used for binding
        musicGroupList.remove(musicGroupToRemove);

        // commit transation
        entityManager.getTransaction().commit();

    }//GEN-LAST:event_deleteSelectedMusicGroup

    private void jButton4exitForm(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4exitForm

        // enable parent form
        parent.setEnabled(true);
        // close current form and destroy all the attached resources
        dispose();
    }//GEN-LAST:event_jButton4exitForm


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JScrollPane jScrollPane1;
    private java.util.List<model.MusicGroup> musicGroupList;
    private javax.persistence.Query musicGroupQuery;
    private javax.swing.JTable musicGroupTable;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
